package com.example.coroutine.net

import com.example.coroutine.bean.ListingResponse
import okhttp3.HttpUrl
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import com.example.coroutine.bean.Result
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query


interface RedditApi {

    @GET("/r/{subreddit}/hot.json")
    suspend fun getTop(
        @Path("subreddit") subreddit: String,
        @Query("limit") limit: Int): Result<ListingResponse>

    companion object {

        private const val BASE_URL = "https://www.reddit.com/"

        private fun create(httpUrl: HttpUrl = BASE_URL.toHttpUrlOrNull()!!): RedditApi {

            val logger = HttpLoggingInterceptor(HttpLoggingInterceptor.Logger.DEFAULT)
            logger.level = HttpLoggingInterceptor.Level.BASIC

            val client = OkHttpClient.Builder()
                .addInterceptor(logger)
                .build()

            return Retrofit.Builder()
                .baseUrl(httpUrl)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(RedditApi::class.java)
        }

        private var instance: RedditApi? = null

        fun getInstance(): RedditApi {

            return instance ?: synchronized(this) {
                instance ?: instance.let {
                    instance = create()
                    return@let instance!!
                }
            }
        }
    }

}